#define MINIAUDIO_IMPLEMENTATION
#include "mp3_player.h"
#include "utf-8_to_gbk.h"

ma_engine engine;
ma_sound sound;
int is_paused = 0;
char* msg;
int running = 1;
uint32_t mp3_id = 0xFFFFFFFF;
ma_uint64 pause_position = 0; // 保存暂停时的位置

// 获取播放状态文本
const char* get_playback_status(int is_paused) {
    return is_paused ? "PAUSED" : "PLAYING";
}

#include <stdint.h>

void mp3_player_init_engine() {
    ma_result result;

    printf("开始初始化音频引擎...\n");
    printf("引擎结构体大小: %zu bytes\n", sizeof(engine));
    printf("引擎指针地址: %p\n", (void*)&engine);
    printf("内存对齐检查: %s\n",
           ((uintptr_t)&engine % 16 == 0) ? "对齐正常" : "可能未对齐");
    fflush(stdout);

    // 使用堆分配确保对齐
    static ma_engine* pEngine = NULL;
    if (pEngine == NULL) {
        pEngine = malloc(sizeof(ma_engine));
        if (pEngine == NULL) {
            printf("内存分配失败！\n");
            return;
        }
    }

    ma_engine_config engineConfig = ma_engine_config_init();
    result = ma_engine_init(&engineConfig, pEngine);

    if (result == MA_SUCCESS) {
        engine = *pEngine;  // 复制到全局变量
        printf("音频引擎初始化成功！\n");
    } else {
        printf("音频引擎初始化失败！错误码: %d\n", result);
        free(pEngine);
        pEngine = NULL;
    }

    fflush(stdout);
}

void mp3_load_for_track(uint32_t track_id){
    //停止当前音乐
    mp3_stop_current();

    ma_result result;

    printf("开始加载音乐文件...\n");

    // 构建歌词文件路径
    const char *filename = _lv_demo_music_get_filename(track_id);
    if (!filename || strcmp(filename, "null") == 0) {
        printf("文件名无效或为null\n");
        return;
    }

    printf("原始文件名: %s\n", filename);

    char mp3_path[256];
    snprintf(mp3_path, sizeof(mp3_path), "%s\\%s.mp3", soft_base_path_resource_mp3, filename);
    printf("完整MP3路径: %s\n", mp3_path);

    // 检查文件是否存在（使用原始路径）
    FILE* test_file = fopen(mp3_path, "rb");
    if (!test_file) {
        printf("错误：音乐文件不存在 - %s\n", mp3_path);

        // 尝试GBK编码路径
        char* gbk_path = utf8_to_gbk(mp3_path);
        test_file = fopen(gbk_path, "rb");
        if (test_file) {
            printf("使用GBK编码找到文件\n");
            fclose(test_file);
            // 使用GBK路径加载
            ma_sound_config soundConfig = ma_sound_config_init();
            soundConfig.pFilePath = gbk_path;
            soundConfig.flags = MA_SOUND_FLAG_NO_SPATIALIZATION;

            result = ma_sound_init_ex(&engine, &soundConfig, &sound);
            free(gbk_path);
        } else {
            printf("GBK编码路径也找不到文件\n");
            free(gbk_path);
            return;
        }
    } else {
        fclose(test_file);
        printf("音乐文件存在性检查通过\n");

        // 使用原始路径加载
        ma_sound_config soundConfig = ma_sound_config_init();
        soundConfig.pFilePath = mp3_path;
        soundConfig.flags = MA_SOUND_FLAG_NO_SPATIALIZATION;

        result = ma_sound_init_ex(&engine, &soundConfig, &sound);
    }

    if (result != MA_SUCCESS) {
        printf("加载音频文件失败！错误码: %d\n", result);

        // 详细错误信息
        switch(result) {
            case MA_INVALID_FILE:
                printf("MA_INVALID_FILE: 文件格式无效或文件损坏\n");
                break;
            case MA_NOT_IMPLEMENTED:
                printf("MA_NOT_IMPLEMENTED: 不支持的音频格式\n");
                break;
            case MA_NO_BACKEND:
                printf("MA_NO_BACKEND: 无可用音频后端\n");
                break;
            default:
                printf("未知错误\n");
        }
        return;
    }

    printf("音乐文件加载成功！\n");

    // 获取并显示音乐信息
    ma_uint64 length_in_frames;
    if (ma_sound_get_length_in_pcm_frames(&sound, &length_in_frames) == MA_SUCCESS) {
        int duration_seconds = (int)(length_in_frames / ma_engine_get_sample_rate(&engine));
        printf("音乐时长: %d分%d秒\n", duration_seconds / 60, duration_seconds % 60);
    }

    //播放音乐
    play_music();
}

void play_music(){
    // 设置循环播放（可选）
    ma_sound_set_looping(&sound, MA_FALSE);

    // 开始播放
    ma_sound_start(&sound);

    printf("正在播放\n");
    printf("=================================\n");
}

void show_status(){
    // 显示初始状态
    msg = utf8_to_gbk("状态: %s\n");
    printf(msg, get_playback_status(is_paused));
    free(msg);
}

void mp3_free(){
    // 清理资源
    ma_sound_uninit(&sound);
    ma_engine_uninit(&engine);
    msg = utf8_to_gbk("\n播放器已退出。\n");
    printf("%s", msg);
    free(msg);
}

/**
 * @brief 设置当前播放的MP3
 * @param track_id 歌曲ID
 */
void lv_demo_music_mp3_set_track(uint32_t track_id)
{
    if (track_id == mp3_id) {
        return; // 已经是当前歌曲
    }
    printf("成功进入lv_demo_music_mp3_set_track");

    mp3_id = track_id;
    mp3_load_for_track(track_id);
}

/**
 * @brief 暂停当前播放的MP3
 */
void mp3_pause(){
    ma_sound_get_cursor_in_pcm_frames(&sound, &pause_position);
    ma_sound_stop(&sound);
    is_paused = 1;
    printf(">>> 播放已暂停\n");
    free(msg);
}

/**
 * @brief 播放当前播放的MP3
 */
void mp3_resume_playback(){
    // 恢复播放 - 定位到暂停位置并开始播放
    ma_sound_seek_to_pcm_frame(&sound, pause_position);
    ma_sound_start(&sound);
    is_paused = 0;
    printf(">>> 播放已恢复\n");
}

/**
 * @brief 只停止当前音乐，不清理引擎
 */
void mp3_stop_current() {
    if (ma_sound_is_playing(&sound)) {
        ma_sound_stop(&sound);
    }
    ma_sound_uninit(&sound);
    is_paused = 0;
    pause_position = 0;
    printf(">>> 已停止当前播放\n");
}

/**
 * @brief 跳转到制定秒数
 * @param track_id 歌曲ID
 */
void seek_to_seconds(int32_t seconds) {
    printf(">>> 跳转函数入口 - seconds地址: %p, 值: %d\n", &seconds, seconds);

    ma_uint32 sampleRate = ma_engine_get_sample_rate(&engine);
    ma_uint64 target_frame = (ma_uint64)(seconds * sampleRate);

    // 获取音频总长度
    ma_uint64 total_frames;
    if (ma_sound_get_length_in_pcm_frames(&sound, &total_frames) != MA_SUCCESS) {
        printf(">>> 无法获取音频长度\n");
        return;
    }

    printf(">>> 计算后 - seconds: %d, target_frame: %llu, total_frames: %llu\n",
           seconds, target_frame, total_frames);

    // 确保目标位置不超过音频长度
    if (target_frame > total_frames) {
        target_frame = total_frames;
        printf(">>> 已跳转到音频末尾\n");
    } else {
        printf(">>> 已跳转到 %.1f 秒 (seconds=%d)\n", (float)seconds, seconds);
    }

    // 保存当前播放状态
    int was_playing = ma_sound_is_playing(&sound);
    printf(">>> 跳转前播放状态: %s\n", was_playing ? "播放中" : "已暂停");

    // 获取跳转前的位置
    ma_uint64 cursor_before;
    ma_sound_get_cursor_in_pcm_frames(&sound, &cursor_before);
    printf(">>> 跳转前位置: %llu 帧 (%.2f 秒)\n", cursor_before, (double)cursor_before / sampleRate);

    // 如果正在播放，先停止以刷新缓冲区
    if (was_playing) {
        ma_sound_stop(&sound);
        printf(">>> 停止音频以刷新缓冲区\n");
    }

    // 跳转到指定位置
    if (ma_sound_seek_to_pcm_frame(&sound, target_frame) != MA_SUCCESS) {
        printf(">>> 跳转失败\n");
        return;
    }

    // 获取跳转后的位置
    ma_uint64 cursor_after;
    ma_sound_get_cursor_in_pcm_frames(&sound, &cursor_after);
    printf(">>> 跳转后位置: %llu 帧 (%.2f 秒)\n", cursor_after, (double)cursor_after / sampleRate);

    // 验证跳转是否真的发生了
    if (cursor_after == target_frame) {
        printf(">>> ✅ 跳转成功验证\n");
    } else {
        printf(">>> ❌ 跳转失败: 期望 %llu, 实际 %llu\n", target_frame, cursor_after);
    }

    // 如果之前正在播放，则重新开始播放
    if (was_playing) {
        ma_sound_start(&sound);
        printf(">>> 刷新缓冲区并重新播放\n");

        // 验证播放状态
        ma_sleep(50); // 短暂等待
        printf(">>> 最终播放状态: %s\n", ma_sound_is_playing(&sound) ? "播放中" : "已暂停");
    }

    printf(">>> 跳转完成\n");
}
